package cn.me;

import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotInteractableException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.*;
import java.util.List;
import java.util.Properties;

/**
 *
 */
public class code {

    private static ChromeDriverService service;
    private static String baseUrl = "https://codeforces.ml/problemset/page/";
    private static String chromeDriverPath = "E:\\chromedriver1\\chromedriver.exe";
    private static String problemSetUrl = "https://codeforces.ml/problemset/problem/";
    private static String alltitlePath = "D:\\codeforce\\all.txt";
    private static String allTitleSubmissionPath = "D:\\codeforce\\allTitleSubmission.txt";
    private static String allProblemPath = "D:\\codeforce\\detail.txt";
    private static String tempansUrlPre = "https://codeforces.ml/problemset/status/903/problem/B";
    private static String ansUrlPre = "https://codeforces.ml/problemset/status/";
    private static String submissionPage = "https://codeforces.ml/problemset/submission/";
    private static String submissionCodePath = "D:\\codeforce\\submissionCode\\";


    public static WebDriver getChromeDriver() throws IOException {
        //System.setProperty("webdriver.chrome.driver","D:\\chromedriver\\chromedriver.exe");
        // 创建一个 ChromeDriver 的接口，用于连接 Chrome（chromedriver.exe 的路径可以任意放置，只要在newFile（）的时候写入你放的路径即可）
        service = new ChromeDriverService.Builder().usingDriverExecutable(
                new File(chromeDriverPath)).usingAnyFreePort().build();
        service.start();
        // 创建一个 Chrome 的浏览器实例
        return new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome());
    }


    public static void main(String[] args) throws IOException, InterruptedException {

        final WebDriver driver = code.getChromeDriver();
        //获取题目编号
//        getProblemNum(driver);
        //获取题目的测试案例
//        getproblem(driver);
//        getAnswer(driver);
        getSubmissionCode(driver);
    }

    private static void getAnswer(WebDriver driver) throws IOException, InterruptedException {
        String ansUrl = ansUrlPre;
        //BufferedReader是可以按行读取文件
        FileInputStream inputStream = new FileInputStream(alltitlePath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;
        boolean flag = true;
        driver.get(tempansUrlPre);
        Thread.currentThread().sleep(10000);
        while ((str = bufferedReader.readLine()) != null) {
            //处理 1234E2 sb则为1234 sb2作为 E2
            StringBuffer sb = new StringBuffer();
            StringBuffer sb2 = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                if ((str.charAt(i) >= '0' && str.charAt(i) <= '9') && flag == true) {
                    sb.append(str.charAt(i));
                } else {
                    flag = false;
                    sb2.append(str.charAt(i));
                }
            }
            flag = true;
            System.out.println(sb.toString() + ":::" + sb2.toString());
            String prodeturl = ansUrl + sb.toString() + "/problem/" + sb2.toString();

            try {
                // 让浏览器访问
                driver.get(prodeturl);
                Thread.currentThread().sleep(3000);
                String xpath = "//*[@id=\"pageContent\"]/div[3]/div[6]/table/tbody/tr[2]";

                WebElement table = driver.findElement(By.xpath(xpath));
                String inputtext = table.getText();

                String submissinid = inputtext.split(" ")[0];
                String s = sb.toString() + "/" + sb2.toString() + "/" + submissinid + "\n";
                if (!inputtext.equals("No")) {
                    WriteStringToFile(s, allTitleSubmissionPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void getSubmissionCode(WebDriver driver) throws IOException, InterruptedException {
        String ansUrl = submissionPage;
        //BufferedReader是可以按行读取文件
        FileInputStream inputStream = new FileInputStream(allTitleSubmissionPath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            StringBuffer sb = new StringBuffer();
            String[] split = str.split("/");

            String prodeturl = ansUrl + split[0] + "/" + split[2];


            try {
                String xpath = "//*[@id=\"program-source-text\"]/ol";
                // 让浏览器访问
                if (!split[2].equals("No")) {
                    driver.get(prodeturl);
                    Thread.currentThread().sleep(3000);
                    WebElement table = driver.findElement(By.xpath(xpath));
                    String inputtext = table.getText();
//                System.out.println(inputtext);
                    savaSubmission(inputtext, submissionCodePath, split[0] + split[1]);
                }
            } catch (Exception e) {
                System.out.println("目前是：" + str);
                e.printStackTrace();
            }
        }
    }

    private static void savaSubmission(String n, String pathname, String fileName) {
        try {

            FileWriter fw = new FileWriter(pathname + fileName + ".java", true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.append(n);
            bw.close();
            fw.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void getproblem(WebDriver driver) throws IOException, InterruptedException {

        String urlpro = problemSetUrl;
        String pathname = alltitlePath;
        //BufferedReader是可以按行读取文件
        FileInputStream inputStream = new FileInputStream(pathname);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;
        boolean flag = true;
        boolean newflag = false;
        while ((str = bufferedReader.readLine()) != null) {
            // if(newflag) {
            //处理 1234E2 sb则为1234 sb2作为 E2
            StringBuffer sb = new StringBuffer();
            StringBuffer sb2 = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                if ((str.charAt(i) >= '0' && str.charAt(i) <= '9') && flag == true) {
                    sb.append(str.charAt(i));
                } else {
                    flag = false;
                    sb2.append(str.charAt(i));
                }
            }
            flag = true;
            String prodeturl = urlpro + sb.toString();

            Problem problem = new Problem();
            problem.setUrl(str);
            // 让浏览器访问
            driver.get(prodeturl);
            Thread.currentThread().sleep(5000);
            String xpath = "//*[@id=\"pageContent\"]/div[3]/div[2]/div/div[5]/div[2]/div[1]";
            try {
                WebElement table = driver.findElement(By.xpath(xpath));
                String inputtext = table.getText();

                problem.setInput(inputtext);

                String xpath1 = "//*[@id=\"pageContent\"]/div[3]/div[2]/div/div[5]/div[2]/div[2]";
                WebElement table1 = driver.findElement(By.xpath(xpath1));
                String outputtext = table1.getText();
                problem.setOutput(outputtext);

                WriteDetailToFile(problem);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // }
        }

        //close
        inputStream.close();
        bufferedReader.close();
    }

    public static void WriteToCsv(Problem p) {
        String pathname = "D:\\codeforce\\detail.csv";
        //第一步：设置输出的文件路径
        //如果该目录下不存在该文件，则文件会被创建到指定目录下。如果该目录有同名文件，那么该文件将被覆盖。
        File writeFile = new File(pathname);

        try {
            //第二步：通过BufferedReader类创建一个使用默认大小输出缓冲区的缓冲字符输出流
            BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));

            //第三步：将文档的下一行数据赋值给lineData，并判断是否为空，若不为空则输出

            writeText.newLine();    //换行
            //调用write的方法将字符串写到流中
            writeText.write(p.getUrl() + "," + p.input + "," + p.output);


            //使用缓冲区的刷新方法将数据刷到目的地中
            writeText.flush();
            //关闭缓冲区，缓冲区没有调用系统底层资源，真正调用底层资源的是FileWriter对象，缓冲区仅仅是一个提高效率的作用
            //因此，此处的close()方法关闭的是被缓存的流对象
            writeText.close();
        } catch (FileNotFoundException e) {
            System.out.println("没有找到指定文件");
        } catch (IOException e) {
            System.out.println("文件读写出错");
        }

    }

    public static void WriteDetailToFile(Problem n) {
        String pathname = allProblemPath;
        try {

            FileWriter fw = new FileWriter(pathname, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.append(n.toString());
            bw.close();
            fw.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static void getProblemNum(WebDriver driver) throws IOException, InterruptedException {
        for (int i = 69; i > 0; i--) {
            System.out.println(i + "====");
            String url = getUrl(i);
            // 让浏览器访问
            driver.get(url);

            //延迟30s 手动登录
            Thread.currentThread().sleep(3000);

            // elements。size 获取到行数
            List<WebElement> elements = driver.findElements(By.cssSelector("table.problems tr"));
            StringBuffer sb = new StringBuffer();
            for (int j = 2; j < elements.size(); j++) {
                sb.append(tableCell(driver, j) + "\n");
            }
            WriteStringToFile(sb.toString(), alltitlePath);
            //延迟30s 手动登录
            Thread.currentThread().sleep(10000);
        }
    }

    public static void WriteStringToFile(String n, String pathname) {
//        String pathname = "D:\\codeforce\\all.txt";
        try {

            FileWriter fw = new FileWriter(pathname, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.append(n);
            bw.close();
            fw.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String getUrl(int i) {
        return baseUrl + i;
    }

    public static String tableCell(WebDriver driver, int row) {

        String xpath = "//*[@id=\"pageContent\"]/div[2]/div[6]/table/tbody/tr[" + row + "]/td[1]";
        WebElement table = driver.findElement(By.xpath(xpath));
        String text = table.getText();
        return text;
    }


}